var express = require('express')
    , route = express.Router()
    , logger = require('log4js').getLogger('user.index.js');

var user = require('../../model').user;

route.use((req, res, next) => {
    logger.info(req.originalUrl);
    next();
});

route.get('/add', (req, res) => {
    if (!req.query.name || !req.query.age) {
        return res.send('params error!');
    }
    var test = { id: Date.now(), name: req.query.name, age: req.query.age }
        , con = { "name": req.query.name };

    user.findOne(con, (err, rel) => {
        if (err) return res.send(err);
        if (rel) {
            user.update(con, test, (err, rel) => {
                if (err) return res.send(err);
                console.log('修改用户成功');
                // res.send({ msg: '此用户已存在，更新信息！', new: { name: test.name, age: test.age } });
                res.redirect(301, 'http://localhost:3000/user');
            });
        }
        else {
            rel = new user(test);
            rel.save((err, rel) => {
                if (err) return res.send(err);
                // res.send({ msg: '新增用户成功', info: { name: test.name, age: test.age } });
                console.log('新增用户成功');
                res.redirect(301, 'http://localhost:3000/user');
            });
        }
    });
});

route.get('/', (req, res) => {
    var record = 10;
    if (req.query.record) {
        record = Number(req.query.record);
    }
    user.find({}).select('-_id -id').sort('-age').limit(record).exec((err, rel) => {
        if (err) return res.send(err);
        res.json({ rel });
    });
});

route.get('/about', (req, res) => {
    res.send('about user');
});

module.exports = route;